package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
//路劲匹配器
    private static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;

        //获取本次请求的路径
        String requestURI=request.getRequestURI();
        String[] urls=new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/login",
                "/user/sendMsg"
        };

            //判断本次请求是否需要处理
        boolean check=check(urls,requestURI);

        //不需要处理的放行
        if (check){
            filterChain.doFilter(request,response);
            return;
        }
//        if (request.getSession().getAttribute("user")!=null){
//            //获取前httpSession中用户的id
//          //  long emplid = (long) request.getSession().getAttribute("user");
//            //把id设置到ThreadLocal中
//            long userid = (long) request.getSession().getAttribute("user");
//            BaseContext.setCurrentId(userid);
//            filterChain.doFilter(request,response);
//        }

        //判断移动端用户登陆状态，如果已登陆，直接放行
        Long userId = (Long) request.getSession().getAttribute("user");
        if(userId != null) {

            //把当前登陆用户设置到本地线程中
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request, response);
            return;
        }


        //判断是否登录
        if (request.getSession().getAttribute("employee")!=null){
           //获取前httpSession中用户的id
            long emplid = (long) request.getSession().getAttribute("employee");
            //把id设置到ThreadLocal中
            BaseContext.setCurrentId(emplid);
            filterChain.doFilter(request,response);
            return;
        }
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }



    private boolean check(String[] urls, String requestURI) {
        for (String url:urls){
            boolean match=PATH_MATCHER.match(url,requestURI);
            if (match){
                return true;
            }
        }
        return false;
    }
}
